package ustc.running.broadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

public class MediaButtonReceiver extends BroadcastReceiver {
	private static long eventStartTime = 0;
	private static long eventEndTime = 0;

	@Override
	public void onReceive(Context context, Intent intent) {

		boolean isActionMediaButton = Intent.ACTION_MEDIA_BUTTON.equals(intent
				.getAction());
		if (!isActionMediaButton)
			return;

		KeyEvent event = (KeyEvent) intent
				.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
		if (event == null)
			return;

		boolean isActionUp = (event.getAction() == KeyEvent.ACTION_UP);
		if (!isActionUp && eventStartTime == 0) {
			eventStartTime=System.currentTimeMillis();
		} else if (isActionUp) {
			eventEndTime = System.currentTimeMillis();
			Bundle data = new Bundle();
			data.putLong("event_time",eventEndTime - eventStartTime);
			data.putInt("key_code", event.getKeyCode());
			Intent myIntent = new Intent();
			myIntent.setAction("honest.ustc.COUNT");
			myIntent.putExtras(data);
			context.sendBroadcast(myIntent);

			eventStartTime = 0;
		}
	}
}
